<script setup lang="ts">
import { ref } from 'vue';
import { UserOutlined, LockOutlined, CheckCircleOutlined } from "@ant-design/icons-vue";
import { AdminApi } from "@/api/manage.api.ts";
import { NotificationUtils } from "@/utils/InteractiveUtils.ts";
import { useSystemStore } from "@/store/System.store.ts";
import {useRouter} from "vue-router";

const systemStore = useSystemStore();

const router = useRouter();
const formRef = ref();
const enableLogin = ref(false);
const loginForm = ref({
  loginName: '',
  password: ''
});
const loginRule = {
  loginName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

const roleModal = ref(false);
const roles = ref<ManageRole[]>([]);
const checkedRole = ref<ManageRole | null>(null);
const admin = ref<ManageAdmin | null>(null);
const token = ref<string | null>(null);

const login = async () => {
  if (!formRef.value) { return; }
  formRef.value.validate().then(() => {
    const form = loginForm.value;
    enableLogin.value = true;
    AdminApi.login(form).then(res => {
      token.value = res.token;
      admin.value = res.admin;
      systemStore.setLogin(res.token, res.admin, res.roles);
      if (res.roles.length > 1) {
        roles.value = res.roles;
        roleModal.value = true;
      }else if (res.roles.length == 1) {
        // 直接登录
        checkedRole.value = res.roles[0];
        handleOkChangeRole();
      }else {
        // 没有角色
        NotificationUtils.error("登录失败", "没有分配角色，请联系管理员");
      }
    }).catch(err => {
      NotificationUtils.error("登录失败", err.message || '请检查用户名和密码是否正确');
    }).finally(() => {
      enableLogin.value = false;
    })
  })
}
const reset = () => {
  if (!formRef.value) {
    console.error('Form reference is not defined');
    return;
  }
  formRef.value.resetFields();
}

const selectedRole = (role: ManageRole) => {
  checkedRole.value = role;
}
const handleCloseChangeRole = () => {
  roleModal.value = false;
  checkedRole.value = null;
}

const handleOkChangeRole = () => {
  if (!checkedRole.value) {
    NotificationUtils.error("请选择角色", "请先选择一个角色");
    return;
  }
  systemStore.setRole(checkedRole.value);
  AdminApi.changeRole(checkedRole.value.code).then(res => {
    if (res.length == 0) {
      throw new Error("当前角色没有分配菜单，请联系管理员");
    }
    roleModal.value = false;
    checkedRole.value = null;
    // 这里可以进行页面跳转或其他操作
    systemStore.setMenuData(res);
    systemStore.setRoutes(res);
    NotificationUtils.success("角色选择成功", "欢迎回来，" + admin.value?.nickname);
    // 跳转到首页
    router.replace("/home").then(() => top?.location.reload());
  }).catch(err => {
    NotificationUtils.error("角色切换失败", err.message || '请稍后再试');
  })
}

</script>

<template>
  <div id="ldn-app-page">
    <a-flex justify="center" class="ldn-login">
      <a-flex vertical class="ldn-login-container" justify="center" align="center">
        <a-space>
          头部区域
        </a-space>
        <div class="vh1"></div>
        <a-space>
          <a-card hoverable bordered class="ldn-login-container-card vw30">
            <a-form ref="formRef" layout="vertical" :rules="loginRule" :model="loginForm" @finish="login" @reset="reset" :disabled="enableLogin">
              <a-form-item name="loginName">
                <a-input v-model:value="loginForm.loginName" placeholder="请输入用户名" >
                  <template #prefix>
                    <UserOutlined />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item name="password">
                <a-input-password v-model:value="loginForm.password" placeholder="请输入密码" >
                  <template #prefix>
                    <LockOutlined />
                  </template>
                </a-input-password>
              </a-form-item>
              <a-form-item>
                <a-flex justify="space-between" align="center">
                  <a-button type="primary" html-type="submit" class="w45">登录</a-button>
                  <a-button type="default" html-type="reset" class="w45">重置</a-button>
                </a-flex>
              </a-form-item>
            </a-form>
          </a-card>
        </a-space>
        <div class="vh1"></div>
        <a-space direction="vertical">
          <a-space >
            <a-button type="link">帮助</a-button>
            <a-button type="link">隐私</a-button>
            <a-button type="link">条款</a-button>
          </a-space>
          <a-space>
            Copyright © 2025 vueComponent
          </a-space>
        </a-space>
      </a-flex>
    </a-flex>

    <a-modal
        v-model:open="roleModal"
        title="选择角色"
        centered
        :closable="false"
        destroyOnClose
        :keyboard="false"
        :maskClosable="false"
        @cancel="handleCloseChangeRole"
        @ok="handleOkChangeRole"
    >
      <a-list size="middle" bordered :data-source="roles">
        <template #renderItem="{ item }">
          <a-list-item @click="selectedRole(item)">
            <a-space>
              <CheckCircleOutlined v-if="item.code == checkedRole?.code"/>  {{ item.name }}
            </a-space>
          </a-list-item>
        </template>
      </a-list>
    </a-modal>
  </div>
</template>

<style scoped>

</style>